from src.model.cash_trade import CashTradeModel


class Public:
    def __init__(self, options):
        self.logger = options.get('logger', None)
        self.chatbot = options.get('chatbot', None)

    def countTip(self, quantity):
        '''计算手续费'''
        fee = 0.001  # 标准手续费
        discount = 0.75  # 手续费折扣
        return quantity * fee * discount + 0.00001

    def countProfit(self, buyTradeData: CashTradeModel,
                    sellTradeData: CashTradeModel):
        ''' 统计每单利润
        :param buyTradeData 购买时的交易数据
        :param sellTradeData 卖出时的交易数据
        订单利润负值为亏损，正值为盈利
        '''

        # 卖出时的资产
        sellAsset = float(sellTradeData.origQty)
        # 购买时的资产
        buyAsset = float(buyTradeData.origQty)
        # 如果为正，则盈利，如果为负则亏损
        profit = sellAsset - buyAsset

        message = '订单平仓成功，订单: {orderId}, 利润:{profit}'.format(
            orderId=sellTradeData.orderId, profit=profit)
        self.chatbot.sendmsg(message, tag='countProfit')

    def checkOrder(self, tradeOrderData: CashTradeModel):
        ''' 检查订单
        :param symbol 交易对 BCHUSDT
        :param orderId 下单id
        :return orderStatus, orderSide, tradeOrderData
        '''
        orderStatus = tradeOrderData.status
        res = tradeOrderData.__dict__
        if orderStatus == 'FILLED':
            message = '订单已完成，订单信息：{}'.format(res)
        elif orderStatus == 'CANCELED':
            message = '订单取消，订单信息：{}'.format(res)
        elif orderStatus == 'NEW':
            message = '订单正常，但未成交！订单信息：{}'.format(res)
        elif orderStatus == 'PARTIALLY_FILLED':
            message = '订单部分成交，请注意！订单信息：{}'.format(res)
        else:
            message = '订单状态:{}，订单信息：{}'.format(orderStatus, res)

        self.chatbot.sendmsg(message, tag='checkOrder')

    def isEnoughAsset(self, assetBalance, quantity, price, maxPosition=1):
        ''' 是否有足够的资金
        :param assetBalance: required 当前资产
        :param quantity: required 购买数量
        :param price: required 购买价格
        :param maxPosition: default 1 默认为全仓位
        :type maxPosition: float
        '''
        pay = price * quantity
        free = assetBalance.free  # 可用资产
        locked = assetBalance.locked  # 锁仓
        freePosition = free * maxPosition
        self.logger.info('{}, {}'.format(free, assetBalance.__dict__))
        if freePosition >= pay:
            self.logger.info('账户资产充足')
            return True
        else:
            message = '账户资产不足或已有订单，请查看是否处理'
            self.chatbot.sendmsg(message, tag='isEnoughAsset')
            return False

    def filterExchangeInfo(self, data, symbol, filterType=None):
        symbols = data.get('symbols')
        for item in symbols:
            if item.get('symbol') == symbol:
                filters = item.get('filters')
                if filterType is None:
                    return filters
                else:
                    for filter in filters:
                        if filter['filterType'] == filterType:
                            return filter
                        else:
                            pass

            else:
                pass
        return False

    def priceFilter(self, exchangeInfo, symbol, price):
        ''' 对下单价格进行过滤
        :param exchangeInfo 交易信息
        :param symbol 交易对
        :param quantity 交易数量
        '''
        if price == 0:
            return False

        # 获得交易信息
        filterExchangeInfo = self.filterExchangeInfo(exchangeInfo,
                                                     symbol,
                                                     filterType='PRICE_FILTER')
        # 获取市场最小交易价格，最大交易价和最小记账
        minPrice = float(filterExchangeInfo.get('minPrice', 0))
        maxPrice = float(filterExchangeInfo.get('maxPrice', 0))
        tickSize = float(filterExchangeInfo.get('tickSize', 0))
        # 由于浮点取余会出现精度问题，故需要转整
        if price >= minPrice and price <= maxPrice and int(
            (price - minPrice) % tickSize) == 0:
            return True
        else:
            return False
